package dormouse.vfs;

import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;

/**
 * This class is responsible for creating the roots used by the file system.
 */
public class RootFactory {

	/** The set of all registered rootmaps. */
	private static Set<IRootMap> rootMaps = new HashSet<IRootMap>();

	static {
		IRootMap macMap = new RootMap("Mac OS X", null);
		macMap.setRootPath(RootNames.DESKTOP, "~/Desktop");
		macMap.setRootPath(RootNames.DOCUMENTS, "~/Documents");
		macMap.setRootPath(RootNames.DOWNLOADS, "~/Downloads");
		macMap.setRootPath(RootNames.HOME, "~");
		macMap.setRootPath(RootNames.MOVIES, "~/Movies");
		macMap.setRootPath(RootNames.MUSIC, "~/Music");
		macMap.setRootPath(RootNames.PHOTOS, "~/Pictures");
		macMap.setRootPath(RootNames.APPLICATIONS, "/Applications");
		rootMaps.add(macMap);

		IRootMap linuxMap = new RootMap("Linux", null);
		rootMaps.add(linuxMap);

		IRootMap win7Map = new RootMap("Windows*", "7.*");
		win7Map.setRootPath(RootNames.PHOTOS, "~/My Pictures");
		win7Map.setRootPath(RootNames.MOVIES, "~/My Videos");
		win7Map.setRootPath(RootNames.MUSIC, "~/My Music");
		rootMaps.add(win7Map);
		
		IRootMap urlMap = new RootMap("Internet",null);
		urlMap.setRootPath(RootNames.FACEBOOK, "http://www.facebook.com");
		urlMap.setRootPath(RootNames.GOOGLE_PLUS, "http://plus.google.com");
		urlMap.setRootPath(RootNames.TWITTER,"http://www.twitter.com");
		rootMaps.add(urlMap);

	}

	/**
	 * This method adds a root map to the root map registry.
	 * 
	 * @param rootMap
	 *            the root map to be added.
	 */
	public static void addRootMap(IRootMap rootMap) {
		rootMaps.add(rootMap);
	}

	/**
	 * This method gets the named root.
	 * 
	 * @param name
	 *            the root name
	 * @return a root file
	 * @throws FileSystemException
	 *             if there is a problem resolving the root file
	 */
	public static FileObject getRoot(RootNames name) throws FileSystemException {

		FileObject root = null;
		for (IRootMap rootMap : rootMaps) {
			if (rootMap.isForCurrentOS()) {
				String path = rootMap.getRootPath(name);
				if (path != null) {
					root = PathUtil.resolveFile(path);
				}
				break;
			}
		}

		return root;
	}

	/**
	 * Gets the path for a specified root name
	 * 
	 * @param name
	 *            the name of the root.
	 * @return a string containing the fully qualified URI
	 * @throws FileSystemException
	 *             If there is a problem resolving the root.
	 * @throws URISyntaxException
	 *             if there is a problem converting the URL to a URI.
	 */
	public static String getRootPath(RootNames name)
			throws FileSystemException, URISyntaxException {
		FileObject root = getRoot(name);
		String path = null;
		if (root != null) {
			path = root.toString();
		}

		return path;
	}

}
